import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { message } from 'ant-design-vue'
import router from '@/router'

// 是否为首次获取登录用户
let firstFetchLoginUser = true;

/**
 * 全局权限校验
 */
router.beforeEach(async (to, from, next) => {
   const loginUserStore=useLoginUserStore()
   let loginUser = loginUserStore.loginUser
//    确保页面首次进入，获取用户登录信息
  if (firstFetchLoginUser){
    await loginUserStore.fetchLoginUser()
    loginUser=loginUserStore.loginUser
    firstFetchLoginUser = false
  }
  const toUrl = to.fullPath
  if (toUrl.startsWith('/admin')) {
    if (!loginUser || loginUser.userRole !== 'admin') {
      message.error('没有权限访问')
      next(`/user/login?redirect=${toUrl}`)
      return
    }
  }
  // 放行
  next()
})
